<template>
  <div class="submission-detail">
    <el-container>
      <el-header class="header-class" height="22">
        <div class="header-text">Submission Details</div>
      </el-header>
      <el-main class="container-main">
        <el-form label-position="left" :model="submissionDetailData" :rules="rules" ref="validatorForm"
                 :size="form_size" :label-width="label_width" :show-message="false">
          <el-row>
            <el-col :span="colHalfSpace">
              <el-form-item label="Requester:" class="labelText">
                <el-input :readonly="true" :style="halfInputWidth"
                          v-model="submissionDetailData.user.requesterDomainId"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="colHalfSpace">
              <el-form-item label="Email:" class="labelText">
                <el-input :readonly="true" v-model="submissionDetailData.user.email" :style='halfInputWidth'></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="colHalfSpace">
              <el-form-item label="Submission Date:" class="labelText">
                <el-input :readonly="true" v-model="submissionDetailData.submissionDate"
                          :style="halfInputWidth"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="colHalfSpace">
              <el-form-item label="Phone:" class="labelText">
                <el-input :readonly="true" v-model="submissionDetailData.user.phone" :style="halfInputWidth"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="colHalfSpace">
              <el-form-item label="Endorsed By:" prop="endorserTeamId">
                <permission-slot :readOnly="!functionList.update_submission_details && !functionList.update_endorser"
                                 :labelName="submissionDetailData.endorserTeamId">
                    Team:
                    <el-select v-model="submissionDetailData.endorserTeamId"
                               filterable
                               placeholder="select"
                               @change="changeEndorserTeam"
                               style="width:44.2%">
                      <el-option
                        v-for="team in submissionDetailData.endorserTeam"
                        :key="team.name"
                        :label="team.name"
                        :value="team"></el-option>
                    </el-select>
                </permission-slot>
              </el-form-item>
            </el-col>
            <el-col :span="colHalfSpace">
              <el-form-item label="Endorser:" prop="endorserArray">
                <permission-slot :readOnly="!functionList.update_submission_details && !functionList.update_endorser"
                                 :labelName="this.endorsersString">
                  <el-select
                    v-model="submissionDetailData.endorserArray"
                    filterable
                    multiple
                    placeholder="select"
                    :style="halfInputWidth"
                  >
                    <el-option
                      v-for="item in submissionDetailData.endorsers"
                      :key="item.domainId"
                      :label="item.domainId"
                      :value="item.domainId">
                      <span style="float: left">{{ item.displayName }}</span>
                    </el-option>
                  </el-select>
                </permission-slot>
              </el-form-item>
            </el-col>
          </el-row>
          <div v-if="functionList.update_submission_details || formStatus === 'CREATE_FORM'">
            <el-row>
              <el-col :span="colHalfSpace">
                <el-form-item label="Notify Other Recipients:">
                  Main Category:
                  <el-select v-model="submissionDetailData.changeMainCategory"
                             placeholder="select"
                             filterable
                             @change="onChangeMainCategory"
                             style="width: 36.3%">
                    <el-option
                      v-for="category in submissionDetailData.changeMainCategoryList"
                      :key="category.categoryName"
                      :label="category.categoryName"
                      :value="category">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="colHalfSpace">
                <el-form-item label="Sub Category:">
                  <permission-slot :readOnly="!functionList.update_submission_details"
                                   :labelName="submissionDetailData.changeSubCategory">
                    <el-select v-model="submissionDetailData.changeSubCategory" placeholder="select"
                               filterable @change="onChangeSubCategory"
                               :style="halfInputWidth">
                      <el-option
                        v-for="subCategory in submissionDetailData.changeSubCategoryList"
                        :key="subCategory.subcategoryName"
                        :label="subCategory.subcategoryName"
                        :value="subCategory">
                      </el-option>
                    </el-select>
                  </permission-slot>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label=" ">
                  you can also add Recipients in the text box below when you can't select it.
                  <el-input type="textarea" rows="2" placeholder="Please input something"
                            v-model="submissionDetailData.copyTo" style="width: 78%"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
          <el-row v-else>
            <el-form-item label="Notify Other Recipients:">
              {{ submissionDetailData.copyTo }}
            </el-form-item>
          </el-row>

          <el-row>
            <el-col :span="colHalfSpace">
              <el-form-item label="To fix for TT No:" prop="TTNo">
                <permission-slot :readOnly="!functionList.update_submission_details"
                                 :labelName="submissionDetailData.TTNo">
                  <el-input v-model="submissionDetailData.TTNo" placeholder="TT-00000000;PR-00000000;..."
                            :style="halfInputWidth"></el-input>
                  <span style="font-size: 12px;">(TT-00000000;PR-00000000;...)</span>
                </permission-slot>
              </el-form-item>
            </el-col>
            <el-col :span="colHalfSpace">
              <el-form-item label="TT/PR level:">
                <permission-slot :readOnly="!functionList.update_submission_details"
                                 :labelName="submissionDetailData.TTOrPRLevel">
                  <el-select v-model="submissionDetailData.TTOrPRLevel" filterable
                             placeholder="select" :style="halfInputWidth">
                    <el-option
                      v-for='item in TTOrPRLevels'
                      :key='item.appKeyValue'
                      :label='item.appKeyValue'
                      :value='item.appKeyValue'>
                    </el-option>
                  </el-select>
                </permission-slot>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="">
            <div v-for="item in submissionDetailData.splitedTTNos" :key="item" class="tips">
              <a :href="'http://hkctrtrpdev/HKCTRTRPAPPS/Layouts/SR/DisplayForm.aspx?srnumber='+item" target="blank">http://hkctrtrpdev/HKCTRTRPAPPS/Layouts/SR/DisplayForm.aspx?srnumber={{item}}</a>
            </div>
          </el-form-item>
          <el-row>
            <el-col :span="colHalfSpace">
              <el-form-item label="Type of Change:" prop="typeOfChange">
                <permission-slot :readOnly="!functionList.update_submission_details"
                                 :labelName="submissionDetailData.typeOfChange">
                  <el-select v-model='submissionDetailData.typeOfChange' placeholder='Select' filterable
                             :style="halfInputWidth">
                    <el-option
                      v-for='item in typeOfChangeOptions'
                      :key='item.appKeyValue'
                      :label='item.appKeyValue'
                      :value='item.appKeyValue'>
                    </el-option>
                  </el-select>
                </permission-slot>
              </el-form-item>
            </el-col>
            <el-col :span="colHalfSpace">
              <el-form-item label="Classification of Change:" prop="classificationOfChange">
                <permission-slot :readOnly="!functionList.update_submission_details"
                                 :labelName="this.classificationOfChangeString">
                  <el-select v-model="submissionDetailData.classificationOfChange"
                             placeholder="select" filterable :style="halfInputWidth" multiple collapseTags>
                    <el-option
                      v-for="classificationOfChange in classificationOfChangeOptions"
                      :key='classificationOfChange.appKeyValue'
                      :label='classificationOfChange.appKeyValue'
                      :value='classificationOfChange.appKeyValue'>
                    </el-option>
                  </el-select>
                </permission-slot>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="Change Objective:" class="labelText" prop="changeObjective">
                <permission-slot :readOnly="!functionList.update_submission_details"
                                 :labelName="submissionDetailData.changeObjective">
                  <el-input v-model="submissionDetailData.changeObjective" style="width: 78%"></el-input>
                </permission-slot>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="colHalfSpace">
              <el-form-item label="Related PCRS(s):" class="labelText" prop="relatedPCRS">
                <permission-slot :readOnly="!functionList.update_submission_details"
                                 :labelName="submissionDetailData.relatedPCRS">
                  <el-input v-model="submissionDetailData.relatedPCRS" :style="halfInputWidth"></el-input>
                  <span style="font-size: 12px;">(PCRS000001;PCRS000002;...)</span>
                </permission-slot>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="">
            <div v-for="item in submissionDetailData.splitedPCRS" :key="item" class="tips">
              <a :href='"http://crs/pcrs/pcrs/view-pcrs-detail/"+item' target="blank">http://crs/pcrs/pcrs/view-pcrs-detail/{{item}}</a>
            </div>
          </el-form-item>
        </el-form>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import Bus from '@/common/js/eventBus'
import teamListService from '@/service/team'
import categoryService from '@/service/category'
import appKeyService from '@/service/appKey'
import PermissionSlot from '@/base-components/permission/PermissionSlot.vue'
import _ from 'lodash'
import { REQUEST_FORM } from '@/store/namespaces'
import { createNamespacedHelpers } from 'vuex'

const {mapGetters} = createNamespacedHelpers(REQUEST_FORM)

const PCRS_TYPE = 'PCRS_TYPE'
const PCRS_CLASSIFICATION_OF_CHANGE = 'PCRS_CLASSIFICATION_OF_CHANGE'
const TT_LEVEL = 'TT_LEVEL'

export default {
  components: {
    PermissionSlot
  },
  props: {
    submissionDetailData: {
      type: Object
    },
    compareChangeRequirementData: {
      type: Object
    },
    functionList: {
      type: Object,
      default: function () {
        return {}
      }
    }
  },
  data: function () {
    let isAvailableTTNos = (ttNos) => {
      let isAvailable = true
      for (let ttNo of ttNos) {
        if (!((ttNo.trim().toUpperCase().startsWith('TT-') || ttNo.trim().toUpperCase().startsWith('PR-')) && (ttNo.trim().length > 3))) {
          isAvailable = false
          break
        }
      }
      return isAvailable
    }

    let isAvailableRelatedPCRS = (relatedPCRSs) => {
      let isAvailable = true
      for (let pcrs of relatedPCRSs) {
        let trimedPCRS = pcrs.trim()
        if (!(trimedPCRS.toUpperCase().startsWith('PCRS')) || !(trimedPCRS.length === 10)) {
          isAvailable = false
          break
        }
      }
      return isAvailable
    }

    let validateTTNos = (rule, value, callback) => {
      Bus.$emit('validateTypeOfChange')
      this.submissionDetailData.splitedTTNos = []
      if (!this.submissionDetailData.TTNo || this.submissionDetailData.TTNo.trim().length === 0) {
        return
      }
      let ttNos = this.submissionDetailData.TTNo.split(';')
      if (isAvailableTTNos(ttNos)) {
        this.submissionDetailData.splitedTTNos = ttNos
        callback()
      } else {
        callback(new Error('Please input a valid TT No.'))
      }
    }

    let validateRelatedPCRS = (rule, value, callback) => {
      this.submissionDetailData.splitedPCRS = []
      let trimedRelatedPCRS
      if (this.submissionDetailData.relatedPCRS) {
        trimedRelatedPCRS = this.submissionDetailData.relatedPCRS.trim()
      } else {
        return
      }

      if (trimedRelatedPCRS.endsWith(';')) {
        trimedRelatedPCRS = trimedRelatedPCRS.slice(0, trimedRelatedPCRS.length - 1)
      }
      let relatedPCRSs = trimedRelatedPCRS.split(';')
      if (isAvailableRelatedPCRS(relatedPCRSs)) {
        this.submissionDetailData.splitedPCRS = relatedPCRSs
        callback()
      } else {
        callback(new Error('Please input a valid Related PCRS.such as \'PCRS000001;PCRS000002;...\''))
      }
    }

    let validateTypeOfChange = (rule, value, callback) => {
      // get the change requirement form and check the expectedDate
      if (this.compareChangeRequirementData.expectedDateChange !== '') {
        Bus.$emit('validateExpectedDateChange')
      }
      let selectedTypeOfChange = this.submissionDetailData.typeOfChange
      if (selectedTypeOfChange === '') {
        callback(new Error())
      } else if (selectedTypeOfChange === 'Un-planned') {
        let trimedTTNo = this.submissionDetailData.TTNo
        if (trimedTTNo.length === 0) {
          this.$message({
            showClose: true,
            message: 'TT No cannot be blank when Type of Change is "Un-planned" ',
            type: 'error'
          })
          callback(new Error())
        } else {
          callback()
        }
      } else {
        callback()
      }
    }

    return {
      elSelectLength: 'width: 320px',
      elShortSelectLength: 'width: 203px',
      elInputLength: 'width: 320px',
      normalWidth: 'width: 380px',
      acrossWidth: 'width: 1290px',
      colHalfSpace: 12,
      halfInputWidth: 'width:50%',
      form_size: 'mini',
      label_width: '200px',
      endorsers: [],
      typeOfChangeOptions: [],
      classificationOfChangeOptions: [],
      TTOrPRLevels: [],

      rules: {
        relatedPCRS: [
          {validator: validateRelatedPCRS, trigger: 'blur'}
        ],
        TTNo: [
          {validator: validateTTNos, trigger: 'blur'}
        ],
        endorserArray: [
          {required: true, message: 'endorser'}
        ],
        endorserTeamId: [
          {required: true, trigger: 'change'}
        ],
        typeOfChange: [
          {required: true, validator: validateTypeOfChange, message: 'type of change'}
        ],
        classificationOfChange: [
          {required: true, message: 'Classification of Change', trigger: 'change'}
        ],
        changeObjective: [
          {required: true, message: 'Change Objective', trigger: 'change'}
        ]
      }
    }
  },

  methods: {
    async getTeamList() {
      this.submissionDetailData.endorserTeam = await teamListService.getTeamListResult()
      if (this.submissionDetailData.endorserTeamId) {
        let $this = this
        let index = _.findIndex(this.submissionDetailData.endorserTeam, function (endorser) {
          return endorser.name === $this.submissionDetailData.endorserTeamId
        })
        let teamEndorsers = []
        this.submissionDetailData.endorserTeam[index].teamEndorsers.forEach((item) => {
          teamEndorsers.push(item.users)
        })
        this.submissionDetailData.endorsers = teamEndorsers
      }
    },

    changeEndorserTeam(team) {
      let teamEndorsers = []
      team.teamEndorsers.forEach((item) => {
        teamEndorsers.push(item.users)
      })
      this.submissionDetailData.endorsers = teamEndorsers
      this.submissionDetailData.endorserTeamId = team.name
      this.submissionDetailData.endorserArray = []
    },

    onChangeMainCategory(category) {
      this.submissionDetailData.changeSubCategory = ''
      this.submissionDetailData.copyTo = ''
      this.submissionDetailData.changeMainCategory = category.categoryName
      this.submissionDetailData.changeSubCategoryList = category.subCategory
    },
    onChangeSubCategory(subCategory) {
      this.submissionDetailData.changeSubCategory = subCategory.subCategoryID
      this.submissionDetailData.copyTo = subCategory.firRequirement
    },
    async initCategoriesList() {
      this.submissionDetailData.changeMainCategoryList = await categoryService.findAllCategories()
      if (this.submissionDetailData.changeMainCategory) {
        let $this = this
        let index = _.findIndex(this.submissionDetailData.changeMainCategoryList, function (mainCategory) {
          return mainCategory.categoryName === $this.submissionDetailData.changeMainCategory
        })
        this.submissionDetailData.changeSubCategoryList = this.submissionDetailData.changeMainCategoryList[index].subCategory
      }
    },

    async getTypeOfChangeOptions() {
      let pcrsTypes = await appKeyService.getAppKeysResult(PCRS_TYPE)
      this.typeOfChangeOptions = pcrsTypes.applicationKeyValueList
    },

    async getClassificationOfChangeOptions() {
      let classificationOfChanges = await appKeyService.getAppKeysResult(PCRS_CLASSIFICATION_OF_CHANGE)
      this.classificationOfChangeOptions = classificationOfChanges.applicationKeyValueList
    },

    async getTTOrPRLevelsOptions() {
      let TTLevels = await appKeyService.getAppKeysResult(TT_LEVEL)
      this.TTOrPRLevels = TTLevels.applicationKeyValueList
    }
  },

  created() {
    this.initCategoriesList()
    this.getTeamList()
  },

  mounted() {
    this.getTypeOfChangeOptions()
    this.getClassificationOfChangeOptions()
    this.getTTOrPRLevelsOptions()
  },

  computed: {
    ...mapGetters({
      formStatus: 'formStatus'
    }),
    endorsersString: function () {
      let endorsers = this.submissionDetailData.endorserArray
      let endorsersString = ''
      for (var i in endorsers) {
        endorsersString += endorsers[i] + ';'
      }
      return endorsersString
    },
    classificationOfChangeString: function () {
      let classification = this.submissionDetailData.classificationOfChange
      let classificationOfChangeString = ''
      for (var i in classification) {
        classificationOfChangeString += classification[i] + ';'
      }
      return classificationOfChangeString
    }
  }

}
</script>

<style scoped lang="scss">
  @import './../../../common/css/base.scss';

  .submission-detail {

  }

  .container-main {
    border: 1px solid $base-header-color;
  }

  .header-class {
    @include baseHeader(30px)
  }

  .header-text {
    color: #fff;
    margin-top: 5px;
    font-weight: bold;
  }

  .input-height {
    height: 20px;
  }

  .el-form-item {
    margin-bottom: 10px;
  }

  .comment_style {
    margin-left: 10px;
    color: #666;
  }

  .between-space {
    margin: 0 3px;
  }

  .text-area-bottom-space {
    margin-bottom: 5px
  }

  .tips-message-info {
    padding-left: 0px;
    padding-right: 50px;
  }

  .tips {
    line-height: 1.5
  }

  .comment-class {
    color: #4F91BB;
  }
</style>
